package com.gitee.somenvm.ninerpgitem.api

import com.gitee.somenvm.ninerpgitem.core.item.update
import org.bukkit.Bukkit
import org.bukkit.OfflinePlayer
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import taboolib.common.platform.function.console
import taboolib.common5.util.parseUUID
import taboolib.module.lang.sendLang
import taboolib.module.nms.getItemTag
import taboolib.platform.util.giveItem
import taboolib.platform.util.isAir
import taboolib.platform.util.isNotAir

object ItemApi {
    fun givePlayerNineItem(player: Player, id: String, amount: Int = 1) {
        val item = NineApi.getNineItem(id)?.build(player)
        if (item != null) {
            console().sendLang("give-item", id, amount, player.name)
            player.giveItem(item, amount)
        }
    }

    /**
     * 返回更新后的物品, 会触发 ItemUpdateEvent,NineItemDataInitEvent
     * 同时原物品也会被更新，不想原物品被更新可以克隆一个再调用此方法
     * @param itemStack 需要更新的物品
     * @param player 使用者
     */
    fun updateItem(itemStack: ItemStack, player: Player): ItemStack {
        if (itemStack.isNotAir() &&
            itemStack.getItemTag()["NRI"]?.asCompound()?.isNotEmpty() == true
        ) {
            return itemStack.update(player) {}
        }
        return itemStack
    }

    /**
     * 强制为一个物品绑定玩家
     * @param item 要绑定的物品
     * @param player 玩家(空为解绑)
     */
    fun bindItem(item: ItemStack, player: Player? = null): ItemStack {
        val nbt = item.getItemTag()
        if (player == null) {
            nbt.removeDeep("NRI.Bind")
            return item
        } else {
            nbt.putDeep("NRI.Bind", "已绑定")
            nbt.saveTo(item)
        }
        return item
    }

    /**
     * 物品是否被绑定
     */
    fun ItemStack.isBind() =
        getItemTag()
            .getDeep("NRI.Bind")
            ?.asString()
            .isNullOrEmpty()


    /**
     * 获取物品所有者(离线)
     */
    fun ItemStack.getOwner(item: ItemStack): OfflinePlayer? {
        if (item.isAir()) return null
        return item
            .getItemTag()
            .getDeep("NRI.owner")
            ?.asString()
            ?.parseUUID()
            ?.let {
                Bukkit.getOfflinePlayer(it)
            }
    }

    fun ItemStack.setOwner(player: Player) {
        val nbt = getItemTag()
        nbt.putDeep("NRI.owner", player.uniqueId)
        nbt.saveTo(this)
    }

    /**
     * 检测玩家是否有使用此物品的权限
     */
    fun ItemStack.hasPerm(player: Player): Boolean {
        //op
        if (player.hasPermission("ninerpgitem.admin")) return true
        //not op
        return if (isBind())
            (getOwner(this) ?: return true).uniqueId == player.uniqueId else true
    }

}